package com.hyjx.framework.common;

import com.hyjx.framework.common.util.SpringBeanUtil;
import com.hyjx.framework.component.mutidatasource.MutiDataSource;
import com.hyjx.framework.component.task.TaskManager;
import com.hyjx.framework.service.CacheManager;
import com.hyjx.framework.service.ConfigManager;
import com.hyjx.framework.service.SystemService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 公共servlet用于初始化信息
 *
 * @author Administrator
 */
@WebServlet(name = "CommonServlet", urlPatterns = {"/commonServlet"}, loadOnStartup = 2)
public class CommonServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static ServletContext servletContext;
    
    @Override
    public void init() {
        // 获得系统的上下文对象
        servletContext = this.getServletContext();
        
        // 项目spring工具类中设置上下文对象
        SpringBeanUtil.setServletContext(servletContext);
        
        //置正在初始化状态
        SystemService.setSysInitStatus("1");
        
        //初始化系统配置信息
        ConfigManager.init();
        
        // 初始化缓存
        CacheManager.init();
        
        // 初始化任务
        TaskManager.initTask();
        
        //恢复正在初始化状态
        SystemService.setSysInitStatus("0");
        
        //动态多数据源的初始化
        MutiDataSource m = new MutiDataSource();
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        m.setApplicationContext(ctx);
        m.init();
    }
    
    /**
     * 动态设置多数据源
     */
    public static void setMutiDataSource() {
        MutiDataSource m = new MutiDataSource();
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        m.setApplicationContext(ctx);
        m.init();
    }
    
    /**
     * 获得系统的上下文对象
     */
    public static ServletContext getStaticServletContext() {
        return servletContext;
    }
    
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
    
    @Override
    @SuppressWarnings("rawtypes")
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method == null) {
            return;
        }
        // 判断是否为在线编辑器的上传方法
        if (method.equals("uploadckeditor")) {
            String tempPath = "";
            DiskFileItemFactory diskFactory = new DiskFileItemFactory();
            // threshold
            diskFactory.setSizeThreshold(4 * 1024);
            // repository
            diskFactory.setRepository(new File(tempPath));
            
            ServletFileUpload upload = new ServletFileUpload(diskFactory);
            // 上传文件的最大值
            upload.setSizeMax(4 * 1024 * 1024);
            List fileItems;
            String fileName = "";
            try {
                fileItems = upload.parseRequest(req);
                FileItem item = (FileItem) fileItems.get(0);
                String fileType = item.getName().substring(item.getName().lastIndexOf(".") + 1);
                fileName = CommonUtil.getUUID32() + "." + fileType;
                String uploadFile = ConfigManager.getConfig("ckeditor.image.path");
                File newFile = new File(uploadFile + fileName);
                if (!newFile.getParentFile().exists()) {
                    newFile.getParentFile().mkdirs();
                }
                item.write(newFile);
                item.delete();
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            String callback = req.getParameter("CKEditorFuncNum");
            PrintWriter out = resp.getWriter();
            // 回调函数
            out.println("<script type=\"text/javascript\">");
            out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",'"
                    + ConfigManager.getConfig("ckeditor.image.show.url") + fileName + "','')");
            out.println("</script>");
        }
    }
}